<template>
    <div class="page">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名">
                <el-input v-model="form.leaveName"  disabled/>
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="form.departmentId" placeholder="请选择" disabled>
                    <!-- <el-option :label="divName" :value="form.departmentId" /> -->
                    <el-option v-for="item in options" :label="item.name" :value="item.id" :key="item.id"/>
                    
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别">
                <el-radio-group v-model="form.leaveType">
                    <el-radio value="事假">事假</el-radio>
                    <el-radio value="病假">病假</el-radio>
                    <el-radio value="婚假">婚假</el-radio>
                    <el-radio value="丧假">丧假</el-radio>
                    <el-radio value="产假">产假</el-radio>
                    <el-radio value="补休">补休</el-radio>
                    <el-radio value="工伤">工伤</el-radio>
                    <el-radio value="其他">其他</el-radio>
                </el-radio-group>
            </el-form-item>
         
                <!-- 开始日期和结束日期 -->
                <el-form-item label="请假时间" required>
      <el-col :span="11" style="margin-bottom: 15px;">
        <el-form-item prop="startTime">
          <el-date-picker
            v-model="form.leaveStartTime"
            aria-label="请选择开始时间"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY年MM月DD日 HH时"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
             @change="handleStartTimeChange"
          />
        </el-form-item>
      </el-col>
      <el-col class="text-center" :span="2" style="margin-bottom: 15px;">
        <span class="text-gray-500">&emsp;至</span>
      </el-col>
      <el-col :span="11" style="margin-bottom: 15px;">
        <el-form-item prop="endTime">
           <el-date-picker
            v-model="form.leaveEndTime"
            aria-label="请选择开始时间"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY年MM月DD日 HH时"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            @change="handleEndTimeChange"
          />
        </el-form-item>
      </el-col>
       <span>工时（天和小时）&emsp;</span>
      <el-form-item prop="leaveHoursDisplay">
        <el-input v-model="form.leaveHours" disabled />
      </el-form-item>
    </el-form-item>
    <el-form-item label="总工时" >
      <el-input v-model="form.leaveHours"  style="width: 50px"/>
      <span>（小时）</span>
    </el-form-item>
    <el-form-item  label="报到时间">
           <el-date-picker
            v-model="form.leaveReportTime"
            aria-label="请选择报到时间"
            type="datetime"
            placeholder="请选择报到时间"
             format="YYYY年MM月DD日 HH时"
              value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"/>
        </el-form-item>
         
            <el-form-item label="请假事由">
                <el-input v-model="form.leaveReason"  maxlength="140" show-word-limit type="textarea" />
            </el-form-item>
            <el-form-item label="部门领导">
              <h3 style="color: red;"> {{  userName}}</h3>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addlevae">提交</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'

import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import moment from 'moment'
import { useCounterStore } from '@/stores/counter'

const store = useCounterStore()
const router = useRouter()


onMounted(() => {
    // findUser()
})

const form = reactive({
  "leaveId": store.currentUser.userId,
  "leaveName": store.currentUser.name,
  "departmentId":store.currentUser.departmentId,
  "leaveType": "",
  "leaveStartTime": "",
  "leaveEndTime": "",
  "leaveHours": 0,
  "leaveReportTime": "",
  "leaveReason": "",
  "leaderName": "",
  "leaderIds": "",
  "createUser":  store.currentUser.name,
  "updateUser": "",
  "approvalStatusName": "",
  leaveHoursDisplay:""

})

// 处理开始时间改变
const handleStartTimeChange = () => {
  if (form.leaveStartTime && form.leaveHours) {
    const startTime = new Date(form.leaveStartTime);
    const endTime = new Date(startTime.getTime() + form.leaveHours * 60 * 60 * 1000);
    form.leaveEndTime = endTime.toISOString().slice(0, 16).replace('T', ' ');
  }
  calculateLeaveHours();
};

// 处理结束时间改变
const handleEndTimeChange = () => {
  calculateLeaveHours();
};

// 处理请假工时改变
const handleLeaveHoursChange = () => {
  if (form.leaveStartTime && form.leaveHours) {
    const startTime = new Date(form.leaveStartTime);
    const endTime = new Date(startTime.getTime() + form.leaveHours * 60 * 60 * 1000);
    form.leaveEndTime = endTime.toISOString().slice(0, 16).replace('T', ' ');
  }
  calculateLeaveHours();
};

// 处理报到时间改变
const handleReportTimeChange = () => {
  // 可以在这里添加更多报到时间相关的逻辑
};

// 处理报到时间改变
const calculateLeaveHours = () => {
  const startTime = new Date(form.leaveStartTime);
  const endTime = new Date(form.leaveEndTime);

  const startDay = startTime.getDate();
  const sh = startTime.getHours();
  const endDay = endTime.getDate();
  const eh = endTime.getHours();
 
  const startHour =(sh < 9) ? 9 : (sh > 18) ? 18 : sh;
  const endHour = (eh < 9) ? 9 : (eh > 18) ? 18 : eh;
  
  if (form.leaveHours !== undefined && form.leaveHours !== null) {
    let days = 0;
    let hours = 0;
    
    // 完整天计算
    if (startDay < endDay) {
      days = endDay - startDay - 1;

      // 开始天计算
      hours = 18 - startHour - (startHour <13 ? 1 : 0);

      // 结尾天计算
      hours += endHour - 9 - (endHour > 12 ? 1 : 0);

      // 特殊情况：开头结尾都是满的
      hours === 16 ? (hours = 0, days += 2) : 0;

      // 工时满8进一
      hours >= 8 ? (hours -= 8, days += 1) : 0;
    }
    //开头结尾同天计算
    else if(startDay === endDay)
    {
      hours = endHour - startHour - (endHour >= 13 && startHour <= 12 ? 1 : 0);
    }

    // 格式化显示工时
    form.leaveHoursDisplay = `${days}天${hours}小时`;
     form.leaveHours = 8*days+hours;
  } else {
    form.leaveHours = 0;
    form.leaveHoursDisplay = '';
  }

};

// 定义下拉框选项
const options = ref([
  { id: 1, name: 'IF信息部' },
  { id: 2, name: '人力资源部' },
  { id: 3, name: '财务部' },
  { id: 4, name: '销售部' },
  { id: 5, name: '行政部' }
]);

const userName=ref('')
//反填部门经理名称
const handleSelectChange  = () => {
    console.log(form.departmentId)
    let aa=[]
    axios.get('/api/User/QueryPowerName',{
        params:{
            DepartmentId:store.currentUser.departmentId,
            UserId:store.currentUser.userId
        }
    }).then((res=>{
        userName.value = res.data.data
    }))
}





    
        // leaveName: store.currentUser.name,
        // departmentId: store.currentUser.departmentId,
        // leaveType:form.leaveType,
        // leaveStartTime: form.leaveStartTime,
        // leaveEndTime: form.leaveEndTime,
        // leaveHours:form.leaveHours,
        // leaveReportTime: form.leaveReportTime,
        // leaderName: userName.value,
        // leaveReason: form.leaveReason,
        // createUser: store.currentUser.name,



const addlevae = () => {
    if(form.leaveReason.length>140){
        ElMessage.error('请假原因不能超过140字')
        return
    }
    axios.post('/api/User/CreateLeave', form)
        .then(res => {
            if (res.data.code == 100) {
                ElMessage.success('添加成功')
                router.push('/LeaveList')
            }
            else {
                ElMessage.error('添加失败')
            }
        })
}

onMounted(()=>{
    handleSelectChange()
})

</script>

<style>
.page {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.demo-ruleForm {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.el-form-item {
    margin-bottom: 20px;
}

.el-input,
.el-select,
.el-date-editor {
    width: 100%;
}

.el-button {
    margin-right: 10px;
}
</style>